/*
 *    Copyright 2022 jacky4631 shen ji email:121659050@qq.com
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dataoke.shoppingguide.app773026.activity.subcategory;

import static com.dataoke.shoppingguide.app773026.bean.Constants.DA_TAO_KE_GOODS_LIST_URL;
import static com.dataoke.shoppingguide.app773026.bean.Constants.PRODUCT_ID_KEY;
import static com.dataoke.shoppingguide.app773026.bean.Constants.PRODUCT_LIST_URL;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alibaba.fastjson.JSON;
import com.dataoke.shoppingguide.app773026.R;
import com.dataoke.shoppingguide.app773026.activity.detail.DataokeProductDetailActivity;
import com.dataoke.shoppingguide.app773026.adapter.DataokeProductListAdapter;
import com.dataoke.shoppingguide.app773026.base.fragments.BaseFragment;
import com.dataoke.shoppingguide.app773026.bean.dataoke.DataokeGoodsDetailBean;
import com.dataoke.shoppingguide.app773026.bean.dataoke.DataokeGoodsListResBean;
import com.dataoke.shoppingguide.app773026.util.HttpTools;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 *
 * @author: shen ji
 * @date: 2022/3/15
 * @email: 121659050@qq.com
 * @wechat: jacky4631
 */
public class HomeDataokeFragment extends BaseFragment implements
        DataokeProductListAdapter.OnItemClickListener,
        OnRefreshLoadMoreListener {
    protected SmartRefreshLayout mRefreshLayout;
    protected TextView mNoData;
    protected DataokeProductListAdapter mProductListAdapter;
    private int page = 1;
    private boolean replace = false;

    private String cids;
    private String upperPrice;
    private String subCids;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_main;
    }
    public static HomeDataokeFragment newInstance(String cids,String upperPrice) {
        return newInstance(cids, upperPrice, false);
    }
    public static HomeDataokeFragment newInstance(String cids,String upperPrice, boolean sub) {
        Bundle bundle = new Bundle();
        if(sub) {
            bundle.putString("subCids", cids);
        } else {
            bundle.putString("cids", cids);
        }
        bundle.putString("upperPrice", upperPrice);

        HomeDataokeFragment homeDataokeFragment = new HomeDataokeFragment();
        homeDataokeFragment.setArguments(bundle);
        return homeDataokeFragment;
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.cids =  getArguments().getString("cids");
        this.upperPrice = getArguments().getString("upperPrice");
        this.subCids = getArguments().getString("subCids");
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        mProductListAdapter = new DataokeProductListAdapter(this);
        RecyclerView recycler = root.findViewById(R.id.recycler);
        mRefreshLayout = mRoot.findViewById(R.id.refreshLayout);
        mRefreshLayout.setEnableFooterFollowWhenNoMoreData(true);
        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        mNoData = mRoot.findViewById(R.id.tv_no_data);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        recycler.setLayoutManager(layoutManager);
        recycler.setAdapter(mProductListAdapter);
        mProductListAdapter.setOnItemClickListener(this);

        //recycler添加和删除动画
        recycler.setItemAnimator(new DefaultItemAnimator());
    }

    protected void initData() {
        HttpTools.get(String.format(DA_TAO_KE_GOODS_LIST_URL, page, upperPrice) + getCids(), new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("HaodankuListFragment", String.format(PRODUCT_LIST_URL, page) + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                DataokeGoodsListResBean productListBean = JSON.parseObject(response.body().string(), DataokeGoodsListResBean.class);
                if(productListBean.getCode() == 0 && !productListBean.getData().getList().isEmpty()) {
                    refreshData(productListBean.getData().getList());
                } else {

                    getActivity().runOnUiThread(() -> {
                        mNoData.setVisibility(View.VISIBLE);
                    });
                }
            }
        });

    }

    protected String getCids() {
        if(!TextUtils.isEmpty(subCids)) {
            return "&subcid=" + subCids;
        }
        if(!TextUtils.isEmpty(cids)) {
            return "&cids=" + cids;
        }
        return "";
    }

    protected void refreshData(List<DataokeGoodsDetailBean> items) {
        getActivity().runOnUiThread(() -> {
            if(replace) {
                mProductListAdapter.setData(items);
            } else {
                mProductListAdapter.addData(items);
            }

            replace = false;

        });
    }

    @Override
    public void onItemClick(int position, DataokeGoodsDetailBean itemBean) {
        Intent intent = new Intent(getContext(), DataokeProductDetailActivity.class);
        intent.putExtra(PRODUCT_ID_KEY, itemBean.getGoodsId());
        getContext().startActivity(intent);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        initData();
        refreshLayout.finishLoadMore(0, true, false);
//        refreshLayout.getLayout().postDelayed(() -> {
////            if (mAdapter.getCount() > 12) {
////                Toast.makeText(getBaseContext(), "数据全部加载完毕", Toast.LENGTH_SHORT).show();
////                refreshLayout.finishLoadMoreWithNoMoreData();//设置之后，将不会再触发加载事件
////            } else {
////                mAdapter.loadMore(loadModels());
//
//
////            }
//        }, 100);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        //            mRefreshLayout.setEnableRefresh(false);
        refreshLayout.getLayout().postDelayed(() -> {
            replace = true;
            page = 1;
            initData();
            refreshLayout.finishRefresh();
            refreshLayout.resetNoMoreData();//setNoMoreData(false);//恢复上拉状态
        }, 1500);
    }
}
